package br.com.aquinoevasconcelos.filtros;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.aquinoevasconcelos.user.UsuarioCliente;

/**
 * Servlet Filter implementation class FiltroCliente
 */

@WebFilter("/FiltroCliente")
public class FiltroCliente implements Filter {

	public FiltroCliente() {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;

		HttpSession session = httpRequest.getSession(false);

		try {

			UsuarioCliente cliente = (UsuarioCliente) session
					.getAttribute("sessaoCliente");

			if (cliente != null) {

				chain.doFilter(request, response);
			}

			else {
				RequestDispatcher view = request.getRequestDispatcher("Index");
				view.forward(request, response);
			}

		} catch (Exception e) {
			RequestDispatcher view = request.getRequestDispatcher("Index");
			view.forward(request, response);
		}
	}

	public void destroy() {

	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
